package org.elsfs.cloud.common.mybatis.injector.methods;

import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.baomidou.mybatisplus.core.toolkit.sql.SqlScriptUtils;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlSource;
import org.elsfs.cloud.common.mybatis.ext.mybatis.extension.JoinWrapper;

/**
 * 查询连表统计
 *

 */
public class SelectJoinCount extends AbstractJoinMethod {
    /**
     * SQL脚本
     */
    private static final String SQL_SCRIPT = "<script>%s SELECT COUNT(%s) FROM %s %s %s %s\n</script>";

    public SelectJoinCount() {
        super("selectJoinCount");
    }


    /**
     * 注入自定义 MappedStatement
     *
     * @param mapperClass mapper 接口
     * @param modelClass  mapper 泛型
     * @param tableInfo   数据库表反射信息
     * @return MappedStatement
     */
    @Override
    public MappedStatement injectMappedStatement(Class<?> mapperClass, Class<?> modelClass, TableInfo tableInfo) {
        String sql = String.format(
            SQL_SCRIPT,
            this.sqlFirst(),
                "1",
            tableInfo.getTableName() + " AS " + JoinWrapper.TABLE_ALIAS,
            SqlScriptUtils.unSafeParam(JOIN_SQL_METHOD),
            this.sqlWhereEntityWrapper(true, tableInfo),
            this.sqlComment()
        );

        SqlSource sqlSource = languageDriver.createSqlSource(configuration, sql, modelClass);
        return this.addSelectMappedStatementForOther(mapperClass, this.methodName, sqlSource, Long.class);
    }
}
